'''
Copyright 2013 Matthew Ramina

This file is part of The Time Machine.

    The Time Machine is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    The Time Machine is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with The Time Machine.  If not, see <http://www.gnu.org/licenses/>.
'''
import sys
import os
import random
import shelve
from PyQt4 import QtGui, QtCore
from window.gui import Ui_MainWindow
from engine.game import Game


deathQuips = ["You suck.", "You suck at this game.", "Even my grandmother is better than you."]


class MyWindow(QtGui.QMainWindow):  # random init stuff
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        """Makes hitting return work"""
        QtCore.QObject.connect(self.ui.lineEdit,
                               QtCore.SIGNAL("returnPressed()"), self.command)
        QtCore.QObject.connect(self.ui.actionLoad,
                               QtCore.SIGNAL("triggered()"), self.loadGame)
        QtCore.QObject.connect(self.ui.actionSave,
                               QtCore.SIGNAL("triggered()"), self.saveGame)
        QtCore.QObject.connect(self.ui.actionBrowseToGames,
                               QtCore.SIGNAL("triggered()"), self.openGameFolder)
        self.ui.questionProgress.setValue(0)
        QtCore.QTimer.singleShot(0, self.start)  # starts the game
        self.answers = []
        self.newGame = False

    def command(self):
        text = self.ui.lineEdit.text()
        self.ui.lineEdit.clear()  # gets the text in box and clears it
        self.write("> %s" % text)  # writes it to the screen
        parsed = play.parser(text)  # parses

        if parsed is None:
            self.write("I'm not sure what you mean by that.")
            return
        elif isinstance(parsed, int) and parsed > len(self.answers) and bool(self.answers):
            self.write("That's not a choice!")
            return

        if self.newGame:
            if parsed == 1:
                self.newGame = False
                self.start()
            else:
                sys.exit()
        elif isinstance(parsed, int) and bool(self.answers):
            nextCommand = play.nextCommand(self.answers[parsed - 1][1])  # fires command
        elif isinstance(parsed, int) and not bool(self.answers):
            nextCommand = play.nextCommand(parsed)
        elif isinstance(parsed, tuple) and parsed[0] == "g":
            play.currentQuestion = play.questions[parsed[1] - 1]
            self.displayQuestion(play.currentQuestion)
            return
        else:
            nextCommand = ""

        if nextCommand is None:
            self.write("I'm not sure what you mean by that.")
        elif nextCommand == "death":
            self.write("You died. " + deathQuips[random.randint(0, len(deathQuips) - 1)])  # finds a death quip and prints it
            self.reset()
            self.write("Play again? (y/[n])")
        elif nextCommand == "win":
            self.write("You win!!!")
            self.reset()
            self.write("Play again? (y/[n])")
        else:
            self.displayQuestion(nextCommand)

    def displayQuestion(self, nextCommand):
        self.write(nextCommand[0])  # writes output of command
        if nextCommand[1] == "":
            pass
        else:
            self.changePic(nextCommand[1])  # changes to appropriate pic

        if nextCommand[2] == []:
            self.write("Press enter to continue")
            self.answers = nextCommand[2:]
        else:
            try:
                self.ui.questionProgress.setValue(int((play.questions.index(nextCommand)) / len(play.questions) * 100))
            except:
                pass
            self.answers = nextCommand[2:]  # make list of answers
            random.shuffle(self.answers)  # shuffle it
            # print(self.answers)
            letters = map(chr, range(97, 97 + len(self.answers)))  # make a list of letters
            for i, j in zip(self.answers, letters):
                self.write(j + ". " + i[0])

    def changePic(self, pic, root=False):  # random function that changes the picture
        if not root:  # not working!!
            myPixmap = QtGui.QPixmap("pics/{}/{}".format(play.picfolder, pic))
            # print("pics/{}/{}".format(play.picfolder, pic))
            # print(play.picfolder)
        else:
            myPixmap = QtGui.QPixmap("pics/{}".format(pic))
        myScaledPixmap = myPixmap.scaled(
            self.ui.picLabel.size(), QtCore.Qt.KeepAspectRatio)
        self.ui.picLabel.setPixmap(myScaledPixmap)

    def write(self, text):  # writes to screen w/o annoying dot function
        self.ui.textDisplay.append(text)

    def start(self):  # starts the game
        self.write(play.intro)
        coords = play.searchText()
        for (index, thing) in enumerate(coords):
            self.write(str(index + 1) + ": " + thing)

    def reset(self):
        self.answers = []
        self.newGame = True
        play.reset()

    def loadGame(self):
        pie = shelve.open("save")
        play.currentQuestion = pie["currentQ"]
        play.questions = pie["questions"]
        pie.close()
        self.write("\n")
        self.write("-------Game Loaded-------")
        self.displayQuestion(play.currentQuestion)

    def saveGame(self):
        pie = shelve.open("save")
        pie["currentQ"] = play.currentQuestion
        pie['questions'] = play.questions
        pie.close()
        self.write("Game saved.")

    def openGameFolder(self):
        # SO'd
        fileopeners = {
            'nt': os.startfile,
            'posix': lambda foldername: os.system('xdg-open "%s"' % foldername),
            'os2': lambda foldername: os.system('open "%s"' % foldername)
        }

        fileopeners.get(os.name, os.startfile)(os.getcwd())

if __name__ == "__main__":  # actually starting the application & event loop
    app = QtGui.QApplication(sys.argv)
    myapp = MyWindow()
    myapp.show()
    myapp.changePic("machineroom.jpg", root=True)
    play = Game()
    sys.exit(app.exec_())
